package com.youga.xuapplication.ui.activity;

import android.os.Bundle;
import android.support.v7.widget.Toolbar;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TextView;

import com.google.gson.reflect.TypeToken;
import com.youga.xuapplication.R;
import com.youga.xuapplication.app.XuApplication;
import com.youga.xuapplication.http.GsonRequest;
import com.youga.xuapplication.model.Cost;
import com.youga.xuapplication.model.Tour;
import com.youga.xuapplication.model.TourTask;
import com.youga.xuapplication.model.User;
import com.youga.xuapplication.ui.BaseActivity;

import net.cgsoft.widget.PickerFragment;
import net.cgsoft.widget.https.HttpCallBack;
import net.cgsoft.widget.model.Model;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Locale;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.OnItemSelected;

public class AddTourActivity extends BaseActivity {

    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.date)
    TextView date;
    @Bind(R.id.spinner)
    Spinner spinner;
    @Bind(R.id.branch)
    EditText branch;
    @Bind(R.id.detail)
    TextView detail;
    private User mUser;
    private TourAdapter mTourAdapter;
    private GsonRequest mRequest;
    private Tour mTour;
    private ArrayList<Tour> mTours;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_tour);
        ButterKnife.bind(this);
        init();
    }


    private void init() {
        toolbar.setTitle("任务");
        mRequest = new GsonRequest(this);
        mUser = XuApplication.application.getUser();
        mTourAdapter = new TourAdapter(null);
        spinner.setAdapter(mTourAdapter);
        obtainTask();
    }

    @OnClick({R.id.fab, R.id.date})
    public void OnClick(View view) {
        switch (view.getId()) {
            case R.id.fab:
                if (mTour == null) {
                    showToast("请先选择城市");
                    return;
                }
                submitTask();
                break;
            case R.id.date:
                showPickerDate(null, new PickerFragment.PickerFragmentCallBack() {
                    @Override
                    public void onDateChanged(String year, String monthOfYear, String dayOfMonth) {
                        date.setText(year + "-" + monthOfYear + "-" + dayOfMonth);
                    }
                });
                break;
        }

    }

    @OnItemSelected({R.id.spinner})
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
        mTour = (Tour) mTourAdapter.getItem(position);
    }

    private void obtainTask() {
        HashMap<String, String> params = new HashMap<>();
        mRequest.function(TOUR_TASK_URL, params, new TypeToken<Model<TourTask>>() {
        }, new HttpCallBack<TourTask>() {
            @Override
            public boolean onStart() {
                showProgressDialog();
                return false;
            }

            @Override
            public void onFinish() {
                dismissProgressDialog();
            }

            @Override
            public void onSuccess(Model<TourTask> model) {
                TourTask tourTask = model.getObject();
                mTours = tourTask.getTours();
                mTourAdapter.updateData(mTours);
                displayUi(tourTask);
            }

            @Override
            public void onFailure(String error) {
                showToast(error);
            }
        });

    }

    private void displayUi(TourTask tourTask) {
        date.setText(tourTask.getCreateDate());
        mTour = tourTask.getTour();
        if (mTour != null) {
            spinner.setSelection(mTours.indexOf(mTour));
            String[] split = tourTask.getCreateDate().split("-");
            Calendar calendar = Calendar.getInstance(Locale.CHINA);
            calendar.set(Integer.valueOf(split[0]), Integer.valueOf(split[1]), Integer.valueOf(split[2]));
            int daysOfMonth = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);
            Cost cost = mUser.getCost();
            branch.setText(tourTask.getCityDot() + "");
            int cityDot = tourTask.getCityDot() == 0 ? 1 : tourTask.getCityDot();
            double result = cost.getFixedCost() / daysOfMonth + cost.getVariableCost() * mTour.getDistance() * cityDot;
            detail.setText("固定成本:" + cost.getFixedCost()
                    + "\n变动成本:" + cost.getVariableCost()
                    + "\n总收入:" + result);
        }
    }

    private void submitTask() {
        HashMap<String, String> params = new HashMap<>();
        params.put("tourId", String.valueOf(mTour.getId()));
        params.put("createDate", date.getText().toString());
        String cityDot = branch.getText().toString();
        params.put("cityDot", cityDot.isEmpty() ? "0" : cityDot);
        mRequest.function(ADD_TOUR_TASK_URL, params, new TypeToken<Model<TourTask>>() {
        }, new HttpCallBack<TourTask>() {
            @Override
            public boolean onStart() {
                showProgressDialog();
                return false;
            }

            @Override
            public void onFinish() {
                dismissProgressDialog();
            }

            @Override
            public void onSuccess(Model<TourTask> model) {
                TourTask tourTask = model.getObject();
                displayUi(tourTask);
            }

            @Override
            public void onFailure(String error) {
                showToast(error);
            }
        });

    }

    public class TourAdapter extends BaseAdapter {

        ArrayList<Tour> tours;

        public TourAdapter(ArrayList<Tour> tours) {
            this.tours = tours == null ? new ArrayList<Tour>() : tours;
        }

        public void updateData(ArrayList<Tour> tours) {
            this.tours = tours == null ? new ArrayList<Tour>() : tours;
            notifyDataSetChanged();
        }

        @Override
        public int getCount() {
            return tours.size();
        }

        @Override
        public Object getItem(int position) {
            return tours.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (convertView == null) {
                convertView = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_tour, null);
                holder = new ViewHolder(convertView);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            Tour tour = tours.get(position);
            holder.tourName.setText(tour.getCity());
            return convertView;
        }

        public class ViewHolder {
            @Bind(R.id.tour_name)
            TextView tourName;

            ViewHolder(View view) {
                ButterKnife.bind(this, view);
            }
        }
    }

}
